/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utils;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;

/**
 *
 * @author chocoseb
 */
public class ClosablePane extends javax.swing.JPanel {
    private JTabbedPane _parentContainer;

    public ClosablePane(final JTabbedPane p_parent) {
        _parentContainer = p_parent;
        setOpaque(false);

        JLabel label = new JLabel() {
            public String getText() {
                int i = _parentContainer.indexOfTabComponent(ClosablePane.this);
                if (i != -1) {
                    return _parentContainer.getTitleAt(i);
                }
                return null;
            }
        };

        add(label);
        JButton button = new TabButton();
        add(button);
    }

    private class TabButton extends JButton implements ActionListener {
        public TabButton() {
            setPreferredSize(new Dimension(18, 14));
            setToolTipText(ChocoMessages.message("Close"));
            setContentAreaFilled(false);
            //setFocusable(false);
            setIcon(new ImageIcon(getClass().getResource("/img/close_black.png")));
            addMouseListener(buttonMouseListener);
            addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            int i = _parentContainer.indexOfTabComponent(ClosablePane.this);
            if (i != -1)
            {
                ChocoPane pane = (ChocoPane)_parentContainer.getComponentAt(i);
                if(pane.mustSave())
                {
                    if (pane.informationNotSaved())
                    {
                        _parentContainer.remove(i);
                    }
                }
                else
                {
                    _parentContainer.remove(i);
                }
            }
        }

    }

    private final static MouseListener buttonMouseListener = new MouseAdapter() {
        public void mouseEntered(MouseEvent e) {
            TabButton btn = (TabButton)e.getComponent();
            btn.setIcon(new ImageIcon(getClass().getResource("/img/close_white.png")));
        }

        public void mouseExited(MouseEvent e) {
            TabButton btn = (TabButton)e.getComponent();
            btn.setIcon(new ImageIcon(getClass().getResource("/img/close_black.png")));
        }
    };
}
